package com.briup.estore.common.service.impl;

import com.briup.estore.common.bean.User;
import com.briup.estore.common.dao.IUserDao;
import com.briup.estore.common.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author adam
 * @date 2022/10/11
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    IUserDao userDao;

    @Override
    public Page<User> findAll(String query, int page, int pageSize) throws Exception {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<User> datas = userDao.findByLoginNameContains(query, pageRequest);
        if (datas.isEmpty()) {
            throw new Exception("暂无查询数据");
        }
        return datas;
    }

    @Override
    @Transactional
    public void disable(long id) {
        userDao.disable(id);
    }

    @Override
    @Transactional
    public void enable(long id) {
        userDao.enable(id);

    }

    @Override
    public User login(String loginName, String password) throws Exception {
        //根据用户名去查询用户信息  看看用户是否存在
        User user = userDao.findByLoginName(loginName);
        if (user == null) {
            throw new Exception("用户未注册");
        } else {
            if (user.isLock()) {
                throw new Exception("用户已锁定 请联系管理员");
            }
            if (user.getPasswordMd5().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
                return user;
            } else {
                throw new Exception("用户名密码错误");
            }
        }

    }

    @Override
    public void register(User user) throws Exception {
        User usera = userDao.findByLoginName(user.getLoginName());
        if (usera == null) {
            userDao.save(user);
        } else {
            throw new Exception("用户名已经存在，请更换后重试");
        }

    }

    @Override
    public long countUser() {
        long count = userDao.count();
        return count;
    }

    @Override
    public Map<String, Double> sexRatio() {
        List<User> users = userDao.findAll();
        double sum = users.size();
        double maleCount = users.stream().filter(u -> u.getGender().equals("男")).count();
        double femaleCount = users.stream().filter(u -> u.getGender().equals("女")).count();
        double unKnowCount = users.stream().filter(u -> u == null).count();
        HashMap<String, Double> map = new HashMap<>();
        map.put("男",maleCount/sum);
        map.put("女",femaleCount/sum);
        map.put("未知",unKnowCount/sum);
        return map;
    }



}
